#include "drawwidget.h"
#include <QPainter>

drawWidget::drawWidget(QWidget *parent)
    : QWidget{parent}
    , _color(Qt::white)
{

}

void drawWidget::paintEvent(QPaintEvent *)
{
        QPainter painter(this);

        QRgb* pixels = new QRgb[width() * height()];
        QImage image((uchar*)pixels, width(), height(), QImage::Format_ARGB32);

        for (int x = 0; x < width(); ++x) {
            for (int y = 0; y < height(); ++y) {
                pixels[x + y * width()] = qRgba(0, 0, 0, 255); // 背景颜色
            }
        }
        _color = Qt::green;
        Bresenham(pixels, 10, 10, 400, 500);
        painter.drawImage(0, 0, image);
}

void drawWidget::setpixel(QRgb* pixels, int x, int y)
{
    if (x < width() && y < height())
        pixels[ x + y * width() ] = _color.rgba();
}

void drawWidget::Bresenham(QRgb* pixels, int x0, int y0, int x1, int y1)
{
    int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
    int dy = abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
    int err = (dx > dy ? dx : -dy) / 2;

    while (setpixel(pixels, x0, y0), x0 != x1 || y0 != y1) {
        int e2 = err;
        if (e2 > -dx) { err -= dy; x0 += sx; }
        if (e2 <  dy) { err += dx; y0 += sy; }
    }
}
